<template>
  <div class="app-container" id="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="申请人ID" prop="userId">-->
<!--        <el-input-->
<!--          v-model="queryParams.userId"-->
<!--          placeholder="请输入申请人ID"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="申请人部门ID" prop="deptId">-->
<!--        <el-input-->
<!--          v-model="queryParams.deptId"-->
<!--          placeholder="请输入申请人部门ID"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="请假类型" prop="leaveType">
        <el-select v-model="queryParams.leaveType" placeholder="请选择请假类型" filterable clearable>
          <el-option
            v-for="dict in dict.type.oa_leave_apply_leave_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker filterable clearable
          v-model="queryParams.startTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker filterable clearable
          v-model="queryParams.endTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="请假天数" prop="durationDays">
        <el-input
          v-model="queryParams.durationDays"
          placeholder="请输入请假天数"
          filterable clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 更多查询条件-->
      <template v-if="isShowMore">
        <el-form-item label="请假时长" prop="durationHours">
          <el-input
            v-model="queryParams.durationHours"
            placeholder="请输入请假时长"
            filterable clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="申请时间" prop="applyTime">
          <el-date-picker filterable clearable
                          v-model="queryParams.applyTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm"
                          placeholder="请选择申请时间">
          </el-date-picker>
        </el-form-item>


      </template>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :icon="isShowMore?'el-icon-d-arrow-right':'el-icon-d-arrow-left'" size="mini" type="warning" @click="isShowMore = !isShowMore">更多查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oa:apply:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oa:apply:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['oa:apply:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['oa:apply:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-alert
      v-if="!isAdmin"
      title="仅显示您作为审批人或抄送人的请假申请"
      type="info"
      show-icon
      :closable="false"
      style="margin-bottom: 10px;"
    />

    <div class="apply-container">
      <!-- 普通用户：显示标签页 -->
      <template v-if="!isAdmin">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <!-- 请假记录 -->
          <el-tab-pane label="请假记录" name="myApply">
            <el-table v-loading="loading" :data="myApplyList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" />
              <el-table-column label="请假类型" align="center" prop="leaveType" >
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_leave_apply_leave_type" :value="scope.row.leaveType"/>
                </template>
              </el-table-column>
              <el-table-column label="开始时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="结束时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="请假天数" align="center" prop="durationDays" />
              <el-table-column label="请假时长" align="center" prop="durationHours" width="150"/>
              <el-table-column label="请假事由" align="center" prop="reason" width="200"/>
              <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                  <dict-tag :options="dict.type.oa_leave_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="申请时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="180" fixed="right">
                <template #default="scope">
                  <el-button
                    v-if="scope.row.status === '待审批'"
                    size="mini"
                    type="text"
                    icon="el-icon-s-promotion"
                    @click="handleSubmit(scope.row)"
                    v-hasPermi="['oa:apply:submit']"
                  >
                    发送
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleInfo(scope.row)"
                    v-hasPermi="['oa:apply:query']"
                  >详情</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['oa:apply:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['oa:apply:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 审批记录 -->
          <el-tab-pane label="审批记录" name="approval">
            <el-table v-loading="loading" :data="approvalList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" />
              <el-table-column label="申请人" align="center" prop="applicantName" />
<!--              <el-table-column label="请假类型" align="center" prop="leaveType" />-->
              <el-table-column label="请假类型" align="center" prop="leaveType" >
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_leave_apply_leave_type" :value="scope.row.leaveType"/>
                </template>
              </el-table-column>
              <el-table-column label="开始时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="结束时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="请假天数" align="center" prop="durationDays" />
              <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                  <dict-tag :options="dict.type.oa_leave_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="申请时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="150" fixed="right">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleApprovalDetail(scope.row)"
                    v-hasPermi="['oa:apply:approve']"
                  >处理</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 抄送记录 -->
          <el-tab-pane label="抄送记录" name="copied">
            <el-table v-loading="loading" :data="copiedList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" />
              <el-table-column label="申请人" align="center" prop="applicantName" />
<!--              <el-table-column label="请假类型" align="center" prop="leaveType" />-->
              <el-table-column label="请假类型" align="center" prop="leaveType" >
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_leave_apply_leave_type" :value="scope.row.leaveType"/>
                </template>
              </el-table-column>
              <el-table-column label="开始时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="结束时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="请假天数" align="center" prop="durationDays" />
              <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                  <dict-tag :options="dict.type.oa_leave_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="申请时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120" fixed="right">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleInfo(scope.row)"
                  >查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>

      <!-- 管理员：显示原始表格 -->
      <template v-else>
        <el-table v-loading="loading" :data="applyList" stripe :height="tableHeight">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" width="55" label="序号" align="center" fixed/>
<!--          <el-table-column label="请假类型" align="center" prop="leaveType" />-->
          <el-table-column label="请假类型" align="center" prop="leaveType" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.oa_leave_apply_leave_type" :value="scope.row.leaveType"/>
            </template>
          </el-table-column>
          <el-table-column label="开始时间" align="center" prop="startTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="center" prop="endTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="请假天数" align="center" prop="durationDays" />
          <el-table-column label="请假时长" align="center" prop="durationHours" width="150"/>
          <el-table-column label="请假事由" align="center" prop="reason" width="200"/>
          <el-table-column label="审批人姓名" align="center" prop="approverNames" width="150"/>
          <el-table-column label="抄送人姓名" align="center" prop="ccNames" width="150"/>
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="dict.type.oa_leave_apply_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180" fixed="right">
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 'pending'"
                size="mini"
                type="text"
                icon="el-icon-s-promotion"
                @click="handleSubmit(scope.row)"
                v-hasPermi="['oa:apply:submit']"
              >
                发送
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-info"
                @click="handleInfo(scope.row)"
                v-hasPermi="['oa:apply:query']"
              >详情</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['oa:apply:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['oa:apply:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改请假申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="68%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
<!--      <el-col :span="8">-->
<!--            <el-form-item label="申请人ID" prop="userId">-->
<!--              <el-input v-model="form.userId"  placeholder="请输入申请人ID" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
<!--      <el-col :span="8">-->
<!--            <el-form-item label="申请人部门ID" prop="deptId">-->
<!--              <el-input v-model="form.deptId"  placeholder="请输入申请人部门ID" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
          <el-col :span="8">
            <el-form-item label="请假类型" prop="leaveType">
              <el-select v-model="form.leaveType" placeholder="请选择请假类型">
                <el-option
                  v-for="dict in dict.type.oa_leave_apply_leave_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker filterable clearable
                    v-model="form.startTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm"
                                  @change="calculateDuration"
                    placeholder="请选择开始时间">
                  </el-date-picker>
                </el-form-item>
          </el-col>
          <el-col :span="8">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker filterable clearable
                    v-model="form.endTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm"
                                  @change="calculateDuration"
                    placeholder="请选择结束时间">
                  </el-date-picker>
                </el-form-item>
          </el-col>
      <el-col :span="8">
            <el-form-item label="请假天数" prop="durationDays">
              <el-input v-model="form.durationDays"  placeholder="请输入请假天数" />
            </el-form-item>
      </el-col>
          <el-col :span="8">
            <el-form-item label="请假时长">
              <el-input
                :value="`${form.durationDays || 0} 天 ${form.durationHours || 0} 小时`"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
                <el-form-item label="请假事由" prop="reason">
                  <el-input v-model="form.reason" type="textarea" placeholder="请输入内容" />
                </el-form-item>
          </el-col>
          <el-col :span="24">
                <el-form-item label="附件路径" prop="attachmentPaths">
                  <file-upload v-model="form.attachmentPaths"/>
                </el-form-item>
          </el-col>
<!--          <el-col :span="24">-->
<!--                <el-form-item label="审批人ID列表" prop="approverIds">-->
<!--                  <el-input v-model="form.approverIds" type="textarea" placeholder="请输入内容" />-->
<!--                </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="24">-->
<!--                <el-form-item label="审批人姓名" prop="approverNames">-->
<!--                  <el-input v-model="form.approverNames" type="textarea" placeholder="请输入内容" />-->
<!--                </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="24">-->
<!--                <el-form-item label="抄送人ID列表" prop="ccIds">-->
<!--                  <el-input v-model="form.ccIds" type="textarea" placeholder="请输入内容" />-->
<!--                </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="24">-->
<!--                <el-form-item label="抄送人姓名" prop="ccNames">-->
<!--                  <el-input v-model="form.ccNames" type="textarea" placeholder="请输入内容" />-->
<!--                </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
          <el-form-item label="审批人" prop="approverIds">
            <el-select
              v-model="form.approverIds"
              multiple
              filterable
              placeholder="请选择审批人"
              style="width: 100%"
            >
              <el-option
                v-for="item in allEmpList"
                :key="item.empId"
                :label="item.empName"
                :value="item.empId + ''"
              />
            </el-select>
          </el-form-item>
          </el-col>

          <!-- 抄送人 -->
          <el-col :span="24">
          <el-form-item label="抄送人" prop="ccIds">
            <el-select
              v-model="form.ccIds"
              multiple
              filterable
              placeholder="请选择抄送人"
              style="width: 100%"
            >
              <el-option
                v-for="item in allEmpList"
                :key="item.empId"
                :label="item.empName"
                :value="item.empId + ''"
              />
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.applyId">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;" :disabled="!isAdmin">
                <el-option
                  v-for="dict in dict.type.oa_leave_apply_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
                <el-form-item label="申请时间" prop="applyTime">
                  <el-date-picker filterable clearable
                    v-model="form.applyTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm"
                    placeholder="请选择申请时间">
                  </el-date-picker>
                </el-form-item>
          </el-col>
<!--      <el-col :span="8">-->
<!--            <el-form-item label="删除标记：0-正常，1-删除" prop="delFlag">-->
<!--              <el-input v-model="form.delFlag"  placeholder="请输入删除标记：0-正常，1-删除" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
<!--        <el-button type="success" @click="sendEmails">提 交</el-button>-->
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button type="success" @click="submitAndSend">提交并发送</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 请假申请详情对话框 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="68%" append-to-body>
      <el-descriptions border >
<!--                        <el-descriptions-item label="申请人ID" >{{form.userId}}</el-descriptions-item>-->
<!--                        <el-descriptions-item label="申请人部门ID" >{{form.deptId}}</el-descriptions-item>-->
                        <el-descriptions-item label="请假类型" >
                          <dict-tag :options="dict.type.oa_leave_apply_leave_type" :value="form.leaveType"/>
                        </el-descriptions-item>
                        <el-descriptions-item label="开始时间" >
                            {{ parseTime(form.startTime, '{y}-{m}-{d} {h}:{i}')}}
                        </el-descriptions-item>
                        <el-descriptions-item label="结束时间" >
                            {{ parseTime(form.endTime, '{y}-{m}-{d} {h}:{i}')}}
                        </el-descriptions-item>
                        <el-descriptions-item label="请假天数" >{{form.durationDays}}</el-descriptions-item>
                        <el-descriptions-item label="请假时长">
                          <template v-if="form.durationDays > 0 && form.durationHours > 0">
                            {{ form.durationDays }} 天 {{ form.durationHours }} 小时
                          </template>
                          <template v-else-if="form.durationDays > 0">
                            {{ form.durationDays }} 天
                          </template>
                          <template v-else-if="form.durationHours > 0">
                            {{ form.durationHours }} 小时
                          </template>
                          <template v-else>
                            0 小时
                          </template>
                        </el-descriptions-item>
                        <el-descriptions-item label="请假事由" >{{form.reason}}</el-descriptions-item>
                        <el-descriptions-item label="附件路径" >{{form.attachmentPaths}}</el-descriptions-item>
<!--                        <el-descriptions-item label="审批人ID列表" >{{form.approverIds}}</el-descriptions-item>-->
                        <el-descriptions-item label="审批人姓名" >{{form.approverNames}}</el-descriptions-item>
<!--                        <el-descriptions-item label="抄送人ID列表" >{{form.ccIds}}</el-descriptions-item>-->
                        <el-descriptions-item label="抄送人姓名" >{{form.ccNames}}</el-descriptions-item>
                        <el-descriptions-item label="状态">
                          <dict-tag :options="dict.type.oa_leave_apply_status" :value="form.status"/>
                        </el-descriptions-item>
                        <el-descriptions-item label="申请时间" >
                            {{ parseTime(form.applyTime, '{y}-{m}-{d} {h}:{i}')}}
                        </el-descriptions-item>
<!--                        <el-descriptions-item label="删除标记：0-正常，1-删除" >{{form.delFlag}}</el-descriptions-item>-->
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApply, getApply, delApply, addApply, updateApply, sendEmail, listApproval, listCopied } from "@/api/oa/apply";
import { listUser } from "@/api/system/user";

export default {
  name: "Apply",
  dicts: ['oa_leave_apply_leave_type', 'oa_leave_apply_status'],
  data() {
    return {
      activeTab: 'myApply',
      // 是否显示更多
      isShowMore: false,
      // el-table 高度
      loading: false,
      tableHeight: window.innerHeight - 200,
      // 普通用户各 Tab 数据
      myApplyList: [],
      approvalList: [],
      copiedList: [],
      // 请假申请表格数据(管理员)
      applyList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      openInfo: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        deptId: null,
        leaveType: null,
        startTime: null,
        endTime: null,
        durationDays: null,
        durationHours: null,
        reason: null,
        attachmentPaths: null,
        approverIds: null,
        approverNames: null,
        ccIds: null,
        ccNames: null,
        status: null,
        applyTime: null,
      },
      currentUserEmpName: this.$store.getters.nickName, // 获取当前登录用户名
      isAdmin: this.$store.getters.roles?.includes('admin') || false,
      // 表单参数
      form: {
        applyId: undefined,
        applicantName: '',
        approverIds: [],   // multiple select 必须是数组
        ccIds: [],         // 抄送人
        leaveType: '',     // 请假类型（关键！不能为空）
        startTime: '',
        endTime: '',
        durationDays: 0,
        durationHours: 0,
        reason: ''
      },
      allEmpList: [],
      empList: [],
      empMap: {},
      empLoading: false,
      // 表单校验
      rules: {
        leaveType: [
          { required: true, message: "请假类型不能为空", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const start = this.form.startTime;
              if (start && value) {
                if (new Date(value) <= new Date(start)) {
                  callback(new Error("结束时间必须大于开始时间"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        durationDays: [
          { required: true, message: "请假天数不能为空", trigger: "blur" }
        ],
        durationHours: [
          { required: true, message: "请假时长不能为空", trigger: "blur" }
        ],
        reason: [
          { required: true, message: "请假事由不能为空", trigger: "blur" }
        ],
        approverIds: [
          { required: true, message: "请选择至少一位审批人", trigger: "blur" }
        ],

        applyTime: [
          { required: true, message: "申请时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    // 假设通过 store 获取用户角色
    userRole() {
      return this.$store.getters.role || 'common'; // 改为你的实际字段，如 roles[0]
    },
    isAdmin() {
      return this.userRole === 'admin';
    },
    currentUserId() {
      return this.$store.getters.userId;
    }
  },
  created() {
    this.loadAllEmployees();
    this.setTableHeight();
    window.addEventListener('resize', this.setTableHeight); // 监听窗口大小变化

    if (this.isAdmin) {
      this.loadAllApplications(); // 管理员加载全部数据
    } else {
      this.loadMyApplyList(); // 普通用户默认加载我的请假
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setTableHeight); // 移除事件监听
  },
  methods: {
    loadAllEmployees() {
      listUser({}).then(res => {
        const users = res.rows || [];
        this.allEmpList = users.map(user => ({
          empId: user.userId,
          empName: user.nickName
        }));
        // 构建映射（用于显示姓名）
        users.forEach(user => {
          this.$set(this.empMap, user.userId, user.nickName);
        });
      }).catch(() => {
        this.$message.warning('加载员工列表失败');
      });
    },
    /**
     * 提交并发送邮件（保存 + 发送）
     */
    submitAndSend() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        const approverIds = this.form.approverIds;
        const ccIds = this.form.ccIds;

        // 验证至少有一个审批人
        if (!approverIds || approverIds.length === 0) {
          this.$message.warning("请至少选择一位审批人");
          return;
        }

        // 获取姓名用于显示和邮件内容
        const approverNames = approverIds
          .map(id => this.empMap[id])
          .filter(name => name)
          .join('、');

        const ccNames = ccIds
          .map(id => this.empMap[id])
          .filter(name => name)
          .join('、');

        if (approverIds.length > 0 && !approverNames) {
          this.$message.warning('所选审批人未加载姓名，请稍等或重新选择');
          return;
        }

        // 准备提交数据
        const submitData = { ...this.form };
        submitData.approverIds = approverIds.join(',');
        submitData.ccIds = ccIds.join(',');
        submitData.approverNames = approverNames;
        submitData.ccNames = ccNames;

        // 如果是新增，则设置状态为“待审批”
        if (!this.form.applyId) {
          submitData.status = 'pending'; // 新增时自动设为待审批
        }

        // 先保存数据（新增或更新）
        const request = this.form.applyId ? updateApply(submitData) : addApply(submitData);

        this.loading = true;
        request
          .then(res => {
            if (res.code === 200) {
              this.$message.success("保存成功，正在发送邮件...");

              // ✅ 保存成功后，立即调用 sendEmail 发送邮件
              const emailParams = {
                applyId: res.data?.applyId || this.form.applyId, // 使用返回的 ID
                applicantName: this.currentUserEmpName,
                approverIds: submitData.approverIds,
                ccIds: submitData.ccIds,
                leaveType: submitData.leaveType,
                startTime: submitData.startTime,
                endTime: submitData.endTime,
                durationDays: submitData.durationDays,
                durationHours: submitData.durationHours,
                reason: submitData.reason
              };

              // 调用发送邮件接口
              return sendEmail(emailParams).then(emailRes => {
                if (emailRes.code === 200) {
                  this.$message.success("邮件已发送");
                } else {
                  this.$message.warning("邮件发送失败: " + (emailRes.msg || '未知错误'));
                }
              });
            }
          })
          .then(() => {
            this.open = false;
            this.getList(); // 刷新列表
          })
          .catch(err => {
            console.error("提交或邮件发送失败:", err);
            this.$message.error("操作失败，请重试");
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    handleTabClick(tab) {
      if (tab.name === 'myApply' && this.myApplyList.length === 0) {
        this.loadMyApplyList();
      } else if (tab.name === 'approval' && this.approvalList.length === 0) {
        this.loadApprovalList();
      } else if (tab.name === 'copied' && this.copiedList.length === 0) {
        this.loadCopiedList();
      }
    },

    // 普通用户：我的请假记录（我自己提交的）
    loadMyApplyList() {
      this.loading = true;
      const params = {
        applicantId: this.currentUserId,
        ...this.queryParams // ✅ 合并查询条件（如 startTime, durationDays 等）
      };

      listApply(params).then(res => {
        this.myApplyList = res.rows || [];
        this.total = res.total; // 用于分页组件
      }).catch(err => {
        this.$message.error('加载我的请假记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 普通用户：我需要审批的
    loadApprovalList() {
      this.loading = true;
      // 后端支持查询：当前用户是审批人 的记录
      listApproval().then(res => {
        this.approvalList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载审批记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 普通用户：抄送给我的
    loadCopiedList() {
      this.loading = true;
      // 后端支持查询：当前用户在抄送人列表中
      listCopied().then(res => {
        this.copiedList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载抄送记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 管理员：加载所有请假记录（不加筛选条件）
    loadAllApplications() {
      this.loading = true;
      // 不传任何筛选条件 → 获取全部数据
      listApply({}).then(res => {
        this.applyList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载全部请假记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 提交申请（发送邮件给审批人和抄送人） */
    handleSubmit(row) {
      this.$confirm('确定要提交该请假申请吗？系统将自动发送邮件通知审批人与抄送人。', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // 构造请求参数
        const params = {
          applyId: row.applyId,
          approverIds:row.approverIds,
          ccIds: row.ccIds,
          leaveType: row.leaveType,
          startTime: row.startTime,
          endTime: row.endTime,
          durationDays: row.durationDays,
          durationHours: row.durationHours,
          reason: row.reason,
          applicantName: this.$store.getters.nickName // 当前登录用户姓名
        };
        console.log('即将发送的参数:', params);
        console.log('approverIds 类型:', typeof params.approverIds); // 应该是 "string"
        console.log('approverIds 值:', params.approverIds);         // 应该是 "14" 或 "14,15"

        // 调用发送邮件接口
        this.loading = true;
        sendEmail(params)
          .then(res => {
            if (res && res.code === 200) {
              this.$message.success(res.msg || '提交成功');
            } else {
              this.$message.error(res?.msg || '提交失败');
            }
          })
          .catch(err => {
            console.error('邮件发送失败:', err);
            this.$message.error('网络错误，邮件发送失败！');
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(() => {
        this.$message.info('已取消提交');
      });
    },
    // 计算请假时长
    calculateDuration() {
      const start = this.form.startTime;
      const end = this.form.endTime;

      if (!start || !end) {
        this.form.durationDays = 0;
        this.form.durationHours = 0;
        return;
      }

      const startDate = new Date(start);
      const endDate = new Date(end);

      if (endDate <= startDate) {
        this.$message.warning("结束时间必须大于开始时间");
        this.form.durationDays = 0;
        this.form.durationHours = 0;
        return;
      }

      // 工作时间段（分钟）
      const WORK_HOURS_PER_DAY = 8 * 60; // 8小时 = 480分钟
      const MORNING_START = 8 * 60 + 30; // 8:30 -> 510分钟
      const MORNING_END = 12 * 60;       // 12:00 -> 720分钟
      const AFTERNOON_START = 13 * 60 + 30; // 13:30 -> 810分钟
      const AFTERNOON_END = 18 * 60;     // 18:00 -> 1080分钟

      // 获取某一天的分钟数（从00:00开始）
      function getMinutes(time) {
        const h = time.getHours();
        const m = time.getMinutes();
        return h * 60 + m;
      }

      // 判断时间是否在工作时间内
      function isInWorkTime(minutes) {
        return (
          (minutes >= MORNING_START && minutes <= MORNING_END) ||
          (minutes >= AFTERNOON_START && minutes <= AFTERNOON_END)
        );
      }

      // 计算某一天内有效工作分钟数
      function getWorkMinutesForDay(date) {
        const dayStart = new Date(date);
        const dayEnd = new Date(date);
        dayStart.setHours(0, 0, 0, 0);
        dayEnd.setHours(23, 59, 59, 999);

        const day = new Date(date);
        const dayMinutes = getMinutes(day);

        const startOfDay = dayStart.getTime();
        const endOfDay = dayEnd.getTime();
        const start = Math.max(startDate.getTime(), startOfDay);
        const end = Math.min(endDate.getTime(), endOfDay);

        if (start >= end) return 0;

        const startMinutes = getMinutes(new Date(start));
        const endMinutes = getMinutes(new Date(end));

        let total = 0;

        // 上午段
        if (startMinutes < MORNING_END && endMinutes > MORNING_START) {
          const segStart = Math.max(startMinutes, MORNING_START);
          const segEnd = Math.min(endMinutes, MORNING_END);
          total += Math.max(0, segEnd - segStart);
        }

        // 下午段
        if (startMinutes < AFTERNOON_END && endMinutes > AFTERNOON_START) {
          const segStart = Math.max(startMinutes, AFTERNOON_START);
          const segEnd = Math.min(endMinutes, AFTERNOON_END);
          total += Math.max(0, segEnd - segStart);
        }

        return total;
      }

      let totalMinutes = 0;
      let current = new Date(startDate);
      current.setHours(0, 0, 0, 0);

      const endDay = new Date(endDate);
      endDay.setHours(0, 0, 0, 0);

      // 遍历每一天
      while (current <= endDay) {
        totalMinutes += getWorkMinutesForDay(current);
        current.setDate(current.getDate() + 1);
      }

      // 转换为天和小时
      const days = Math.floor(totalMinutes / WORK_HOURS_PER_DAY);
      const remainingMinutes = totalMinutes % WORK_HOURS_PER_DAY;
      const hours = Math.round(remainingMinutes / 60 * 10) / 10; // 保留1位小数

      this.form.durationDays = days;
      this.form.durationHours = parseFloat(hours.toFixed(1));
    },

    /** 查询请假申请列表 */
    getList() {
      this.loading = true;

      // 构造请求参数
      const params = { ...this.queryParams };

      // 如果不是管理员，则只查询包含当前用户的记录（作为审批人或抄送人）
      if (!this.isAdmin) {
        params.includeMe = true; // 告诉后端：只返回当前用户是审批人或抄送人的记录
        params.currentUserName = this.currentUserEmpName; // 传当前用户名用于匹配
      }

      listApply(params).then(response => {
        this.applyList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.$message.error('加载请假申请列表失败');
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        applyId: null,
        userId: null,
        deptId: null,
        leaveType: null,
        startTime: null,
        endTime: null,
        durationDays: null,
        durationHours: null,
        reason: null,
        attachmentPaths: null,
        approverIds: null,
        approverNames: null,
        ccIds: null,
        ccNames: null,
        status: null,
        applyTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        delFlag: null
      };
      this.resetForm("form");
      this.empList = []; // 清空缓存的员工列表
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.isAdmin) {
        this.getList();
      } else {
        this.loadMyApplyList(); // ✅ 普通用户调用正确的加载方法
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.applyId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加请假申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const applyId = row.applyId || this.ids;
      getApply(applyId).then(response => {
        const data = response.data;
        // 1. 先复制数据
        this.form = { ...data };

        // 2. 将字符串转为数组（注意：split后是字符串数组，要转成数字或保持字符串）
        this.form.approverIds = data.approverIds ? data.approverIds.split(',').map(id => id.trim()) : [];
        this.form.ccIds = data.ccIds ? data.ccIds.split(',').map(id => id.trim()) : [];

        // 3. 加载溢选人员部分
        const selectedUserIds = [
          ...this.form.approverIds,
          ...this.form.ccIds
        ].map(id => parseInt(id)).filter(id => !isNaN(id));

        if (selectedUserIds.length > 0) {
          this.empLoading = true;
          listUser({ userIds: selectedUserIds }) // 查询用户信息
            .then(res => {
              const userData = Array.isArray(res?.rows) ? res.rows : [];
              this.empList = userData.map(u => ({
                empId: u.userId,
                empName: u.nickName
              }));

              // 构建 userId -> nickName 映射
              userData.forEach(u => {
                if (u?.userId && u?.nickName) {
                  this.$set(this.empMap, u.userId, u.nickName);
                }
              });

              this.empLoading = false;
            })
            .catch(err => {
              console.error('加载已选用户失败:', err);
              this.$message.warning('未能加载审批人/抄送人姓名');
              this.empLoading = false;
            });
        } else {
          this.empList = [];
        }

        this.open = true;
        this.title = "修改请假申请";
      });
    },
    /** 详情按钮操作 */
    handleInfo(row) {
      this.reset();
      const applyId = row.applyId || this.ids
      getApply(applyId).then(response => {
        this.form = response.data;
        this.openInfo = true;
        this.title = "请假申请详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        // ✅ 此时 form.approverIds 已经是 empId 数组了
        const approverIds = this.form.approverIds;
        const ccIds = this.form.ccIds;

        // ✅ 可选：根据 empId 获取姓名（用于显示）
        const approverNames = approverIds
          .map(id => this.empMap[id])
          .filter(name => name);

        if (approverIds.length > 0 && approverNames.length === 0) {
          this.$message.warning('所选审批人未在系统中找到对应姓名，请重新选择');
          return;
        }

        // ✅ 准备提交数据
        const submitData = { ...this.form };

        // 数据库字段兼容：ID 列表用逗号分隔
        submitData.approverIds = approverIds.join(',');
        submitData.ccIds = ccIds.join(',');

        // 姓名也保存（可选）
        submitData.approverNames = approverNames.join(',');
        submitData.ccNames = ccIds.map(id => this.empMap[id]).filter(name => name).join(',');

        // 提交
        if (this.form.applyId != null) {
          updateApply(submitData).then(() => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          addApply(submitData).then(() => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const applyIds = row.applyId || this.ids;
      this.$modal.confirm('是否确认删除请假申请编号为"' + applyIds + '"的数据项？').then(function() {
        return delApply(applyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/apply/export', {
        ...this.queryParams
      }, `请假申请数据导出_${new Date().getTime()}.xlsx`)
    },
    // 设置表格高度
    setTableHeight() {
      const appContainer = document.getElementById('app-container');
      if (appContainer) {
        this.tableHeight = appContainer.clientHeight * 0.8;
      }
    }
  },
  mounted() {
    // 动态设置高度
    this.tableHeight = window.innerHeight - 200;
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 200;
    };
  },
};
</script>
<style scoped>
.apply-container {
  padding: 16px;
  background-color: #fff;
}
.el-table {
  margin-top: 10px;
}
</style>
